<template>
  <div>
    <a-modal title="手工拆单" :visible="visible" @before-open="open" @ok.stop="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="1200px" :mask-closable="false">
      <div class="top mt10">
        <div>
          <span>店铺：</span>
          <span>{{ orderItemInfo.shopName }}</span>
        </div>
        <div style="margin-left: 20px">
          <span>订单号：</span>
          <span>{{ orderItemInfo.platformOrderNumber }}</span>
        </div>
        <div style="margin-left: 20px">
          <span>订单来源：</span>
          <span>{{ orderSource() }}</span>
        </div>
        <div style="margin-left: 20px">
          <span class="fl">
            <icon-info-circle-fill style="color: #f59a23" />
          </span>
          <span class="fl" style="margin-left: 5px; color: #f59a23">拆单中的的数量之和不能大于其未发数量，每个拆单中至少有一种商品数量≥1</span>
        </div>
      </div>
      <div class="bottom mt10">
        <div class="left">
          <div class="clearfix">
            <div class="fl">待拆分商品：{{ skuList.length }}</div>
            <div class="fr">
              <a-button type="text" @click="addPackOrder">增加包裹</a-button>
              <a-button type="text" class="ml10" @click="handleOpenForSKU">按SKU一键拆分</a-button>
            </div>
          </div>
          <div class="table-con mt10">
            <a-table class="table-two-line" :pagination="false" size="mini" :data="skuList" :scroll="{ x: '800px', y: '500px' }">
              <template #columns>
                <a-table-column v-for="item of [...columns, ...packageList]" :width="item.width">
                  <template #title>
                    <div class="clearfix" style="width: 100%; user-select: none">
                      <div class="fl">{{ item.title }}{{ item.num != '1' ? item.num : '' }}</div>
                      <div class="fr" @click="delTitle(item)" style="margin-left: 10px; cursor: pointer" v-if="item.isAdd"><icon-close-circle-fill /></div>
                    </div>
                  </template>
                  <template #cell="{ record }" v-if="item.title == '商品信息'">
                    <div class="clearfix" style="width: 150px">
                      <div class="fl">
                        <ImgPopover :src="getImage(record)">
                          <template #con>
                            <img width="40" height="40" :src="getImage(record)" />
                          </template>
                        </ImgPopover>
                      </div>
                      <div class="fl ml10">
                        <div>
                          <span>sku:</span>
                          <span class="highlight">{{ record.productSku }}</span>
                        </div>
                        <div>
                          <span>msku:</span>
                          <span class="highlight">{{ record.msku }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                  <template #cell="{ record }" v-else-if="item.title == '未发数'">
                    {{ record.qtyOrdered }}
                  </template>
                  <template #cell="{ record }" v-else-if="item.title == '包裹1'">
                    <a-input disabled v-model="item.skuNum[record.id]"></a-input>
                  </template>
                  <template #cell="{ record }" v-else>
                    <a-input-number @input="inputNumChange($event, item, record)" v-model="item.skuNum[record.id]" hide-button />
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
        </div>
        <div class="right">
          <div class="clearfix">
            <div class="fl">
              <a-button type="text" @click="createPreview">生成预览</a-button>
            </div>
            <div class="fr">
              <span class="fl" style="margin-top: 6px">统一发货仓：</span>
              <a-select @change="warehouseChange" class="fl" style="width: 180px; height: 28px" v-model="warehouseCode" allow-clear placeholder="请选择" allow-search :fallback-option="() => ''">
                <a-option v-for="item of houseList" :value="item.warehouseCode" :label="item.warehouseName"></a-option>
              </a-select>
            </div>
          </div>
          <div class="list-con mt10">
            <a-empty v-if="autoCreatePackageList.length == 0" description="暂无包裹生成，请先拆单之后点击生成预览" />
            <a-scrollbar v-else style="max-height: 500px; overflow: auto">
              <ul class="auto-create-package-con">
                <li class="mb10" v-for="packageItem of autoCreatePackageList" :key="packageItem.title">
                  <div class="top">
                    <div>{{ packageItem.name }}</div>
                    <div>
                      <span class="fl">自发仓：</span>
                      <a-select class="fl" style="width: 180px" @change="changeSinglePackage($event, packageItem)" v-model="packageItem.warehouseCode" allow-clear placeholder="请选择" allow-search :fallback-option="() => ''">
                        <a-option v-for="item of houseList" :value="item.warehouseCode" :label="item.warehouseName"></a-option>
                      </a-select>
                    </div>
                  </div>
                  <div class="line"></div>
                  <div>
                    <div class="bottom" v-for="productItem of packageItem.productItemList" :key="productItem.id">
                      <div class="fl">
                        <ImgPopover :src="getImage(productItem)">
                          <template #con>
                            <img width="40" height="40" :src="getImage(productItem)" />
                          </template>
                        </ImgPopover>
                      </div>
                      <div class="fl" style="margin-left: 10px; width: 150px">
                        <div style="display: flex">
                          <span>SKU：</span>
                          <!-- <span class="highlight">{{ productItem.productSku }}</span> -->
                          <TextLimit class="highlight" style="width: 100px" position="top" :rows="1">{{ productItem.productSku }}</TextLimit>
                        </div>
                        <div style="display: flex">
                          <span>MSKU：</span>
                          <!-- <span class="highlight">{{ productItem.msku }}</span> -->
                          <TextLimit class="highlight" style="width: 100px" position="top" :rows="1">{{ productItem.msku }}</TextLimit>
                        </div>
                      </div>
                      <div class="fl" style="margin-left: 10px">
                        <div>
                          <span>数量：</span>
                          <span>{{ productItem.splitNum }}</span>
                        </div>
                        <div>
                          <span>可用库存：</span>
                          <span>{{ productItem.amtAvailable || productItem.amtAvailable == 0 ? productItem.amtAvailable : '--' }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
            </a-scrollbar>
          </div>
        </div>
      </div>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button class="ml10" type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed, nextTick } from 'vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { Message } from '@arco-design/web-vue'
  import { splitOrder, findInventoryBatch } from '@/api/order'
  import _ from 'lodash-es'
  import { sortColumns } from '@/utils'
  export default defineComponent({
    props: ['info'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const data: any = reactive({
        orderItemInfo: {},
        skuList: [],
        houseList: [],
        warehouseCode: '',
        columns: [
          { title: '商品信息', width: 140, isAdd: false },
          { title: '未发数', width: 60, isAdd: false },
        ],
        packageList: [
          { title: '包裹1', width: 80, isAdd: false, num: '1', skuNum: {} },
          { title: '包裹', width: 80, isAdd: true, num: '2', skuNum: {} },
        ],
        initPackageObj: {},
        blankPackageObj: {},
        autoCreatePackageList: [],
        loading: false,
      })

      const open = () => {
        data.orderItemInfo = _.cloneDeep(props.info)

        let list = data.orderItemInfo.packageList
        data.skuList = []
        let newSkuList: any = []

        list.forEach((e: any) => {
          let arr = e.packageItemList.map((el: any) => {
            el.oldQtyOrdered = e.qtyOrdered
            el.warehouseCode = e?.warehouseCode || ''
            el.marketplaceId = data.orderItemInfo?.marketplaceId || ''
            el.sellerId = data.orderItemInfo?.sellerId || ''
            return el
          })
          newSkuList = [...newSkuList, ...arr]
        })

        newSkuList.forEach((e: any) => {
          let index = data.skuList.findIndex((el: any) => e.orderItemId == el.orderItemId)
          if (index == -1) {
            data.skuList.push(e)
          }
        })

        getWareHouseList()
        initPakageList()
      }

      const initPakageList = () => {
        data.skuList.forEach((e: any) => {
          data.initPackageObj[e.id] = e.qtyOrdered
          data.blankPackageObj[e.id] = ''
        })
        data.packageList[0].skuNum = _.cloneDeep(data.initPackageObj)
        data.packageList[1].skuNum = _.cloneDeep(data.blankPackageObj)
      }

      const handleOk = async () => {
        if (!data.autoCreatePackageList[0]) {
          return Message.error('请先生成预览')
        }
        let params: any = {
          orderId: data.orderItemInfo.id,
          packageList: [],
        }
        data.autoCreatePackageList.forEach((e: any) => {
          let obj: any = {
            itemList: [],
            warehouseCode: e.warehouseCode,
            warehouseName: e.warehouseName,
          }
          e.productItemList.forEach((el: any) => {
            let obj1: any = {
              orderItemId: el.id,
              qtyShipped: el.splitNum,
            }
            obj.itemList.push(obj1)
          })

          params.packageList.push(obj)
        })
        data.loading = true
        try {
          const res: any = await splitOrder(params)
          if (res.code == 'SUCCESS') {
            Message.success('拆分订单成功')
            handleCancel()
            emit('save')
          }
          data.loading = false
        } catch (error) {
          data.loading = false
        }
      }
      const handleCancel = () => {
        resetPackageList()
        visible.value = false
      }

      const orderSource = () => {
        let text = ''
        if (data.orderItemInfo.source == 'OFFLINE') {
          text = 'API接口'
        }
        return text
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        data.houseList = res?.data
      }

      const getImage = (item: any) => {
        if (item.isCustom) {
          let arr = item.customPics ? item.customPics.split(',') : []
          return arr[0]
        } else {
          return item.productPic
        }
      }

      const addPackOrder = () => {
        let num = data.packageList[data.packageList.length - 1].num
        let obj = {
          title: '包裹',
          width: 80,
          isAdd: true,
          num: parseInt(num) + 1 + '',
          skuNum: _.cloneDeep(data.blankPackageObj),
        }

        data.packageList[data.packageList.length] = obj
      }

      const delTitle = (item: any) => {
        let index = data.packageList.findIndex((el: any) => el.num == item.num)
        let obj = data.packageList[index].skuNum
        for (const key in obj) {
          if (obj[key] && obj[key] > 0) {
            data.packageList[0].skuNum[key] += obj[key]
          }
        }
        data.packageList.splice(index, 1)
      }

      const inputNumChange = _.debounce((value: number, packageItem: any, recordItem: any) => {
        data.autoCreatePackageList = []
        let id = recordItem.id
        let residueNum = 0
        let newVal = value
        let val = 0
        if (value) {
          val = value
        }
        // 每次输入的时候或者剩余的可拆分订单数量
        let arr = data.packageList.filter((e: any) => e.isAdd && e.num != packageItem.num)

        if (arr.length > 0) {
          // 已经用掉的数量
          let useNum = 0
          arr.forEach((e: any) => {
            if (e.skuNum[id]) {
              useNum += e.skuNum[id]
            }
          })
          residueNum = data.initPackageObj[id] - useNum
        } else {
          residueNum = data.initPackageObj[id]
        }

        packageItem.skuNum[id] = ''
        if (val > residueNum) {
          setTimeout(() => {
            packageItem.skuNum[id] = residueNum
            let subPackageNum = 0
            arr.forEach((e: any) => {
              if (e.skuNum[id]) {
                subPackageNum += e.skuNum[id]
              }
            })
            data.packageList[0].skuNum[id] = data.initPackageObj[id] - residueNum - subPackageNum
          }, 100)
        } else {
          let subPackageNum = 0
          arr.forEach((e: any) => {
            if (e.skuNum[id]) {
              subPackageNum += e.skuNum[id]
            }
          })
          packageItem.skuNum[id] = newVal
          data.packageList[0].skuNum[id] = data.initPackageObj[id] - val - subPackageNum
        }
      }, 100)

      const handleOpenForSKU = () => {
        data.autoCreatePackageList = []
        let num = data.skuList.length
        let addNum = num - 1
        resetPackageList()
        for (let i = 1; i < addNum; i++) {
          let num = data.packageList[data.packageList.length - 1].num
          let obj = {
            title: '包裹',
            width: 80,
            isAdd: true,
            num: parseInt(num) + i + '',
            skuNum: _.cloneDeep(data.blankPackageObj),
          }

          data.packageList[data.packageList.length] = obj
        }

        let index = 0
        let obj = data.packageList[0].skuNum
        for (const key in obj) {
          data.packageList[index].skuNum[key] = obj[key]
          if (index > 0) obj[key] = 0
          index++
        }
      }

      const resetPackageList = () => {
        data.autoCreatePackageList = []
        data.packageList = [
          { title: '包裹1', width: 80, isAdd: false, num: '1' },
          { title: '包裹', width: 80, isAdd: true, num: '2' },
        ]
        data.packageList[0].skuNum = _.cloneDeep(data.initPackageObj)
        data.packageList[1].skuNum = _.cloneDeep(data.blankPackageObj)
        data.warehouseCode = ''
      }

      const createPreview = () => {
        let flag = false
        let obj = data.packageList[0].skuNum
        for (const key in obj) {
          if (obj[key]) {
            flag = true
            break
          }
        }
        if (!flag) {
          return Message.error('包裹1必须有一件商品')
        }

        data.autoCreatePackageList = []

        // 判断当前包裹里面是不是都有数据，没有的话跳过循环
        for (let i = 0; i < data.packageList.length; i++) {
          let flag = false
          let skuNum = data.packageList[i].skuNum
          for (const key in skuNum) {
            if (skuNum[key]) {
              flag = true
              break
            }
          }
          if (!flag) {
            continue
          }

          let obj: any = {}
          obj.productItemList = []
          data.packageList[i].num == 1 ? (obj.name = data.packageList[i].title) : (obj.name = `${data.packageList[i].title}${data.packageList[i].num}`)
          for (const key in skuNum) {
            let num = skuNum[key]
            if (num) {
              let product = _.cloneDeep(data.skuList.find((e: any) => e.id == key))
              // let product = data.skuList.find((e: any) => e.id == key)
              product.splitNum = num
              obj.productItemList.push(product)
            }
          }
          obj.warehouseCode = data.warehouseCode ? data.warehouseCode : ''
          obj.warehouseName = ''
          data.autoCreatePackageList.push(obj)
        }
      }

      const warehouseChange = () => {
        data.autoCreatePackageList.forEach((e: any) => {
          e.warehouseCode = data.warehouseCode
        })
        let params: any = {
          inventoryItems: [],
        }

        data.skuList.forEach((e: any) => {
          let obj = {
            warehouseCode: data.warehouseCode,
            // msku: e.msku,
            marketplaceId: e.marketplaceId,
            sellerId: e.sellerId,
            sku: e.productSku,
            key: `${e.orderPackageId}_${e.id}`,
          }
          params.inventoryItems.push(obj)
        })
        getFindInventoryBatch(params, data.autoCreatePackageList)
      }

      const changeSinglePackage = (code: string, item: any) => {
        console.log(code, item)
        let params: any = {
          inventoryItems: [],
        }

        item.productItemList.forEach((e: any) => {
          let obj = {
            warehouseCode: code,
            // msku: e.msku,
            marketplaceId: e.marketplaceId,
            sellerId: e.sellerId,
            sku: e.productSku,
            key: `${e.orderPackageId}_${e.id}`,
          }
          params.inventoryItems.push(obj)
        })
        getFindInventoryBatch(params, [item])
      }

      const getFindInventoryBatch = async (params: any, list: any) => {
        const res: any = await findInventoryBatch(params)
        if (res) {
          list.forEach((el: any) => {
            el.productItemList.forEach((ell: any) => {
              res.data?.inventoryItems.forEach((e: any) => {
                if (e.key == `${ell.orderPackageId}_${ell.id}`) {
                  ell.amtAvailable = e.amtAvailable
                }
              })
            })
          })

          console.log(data.autoCreatePackageList)
        }
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        orderSource,
        getImage,
        addPackOrder,
        delTitle,
        inputNumChange,
        handleOpenForSKU,
        createPreview,
        warehouseChange,
        changeSinglePackage,
      }
    },
  })
</script>

<style lang="less" scoped>
  .top {
    height: 30px;
    line-height: 30px;
    display: flex;
    font-size: 12px;
  }

  .bottom {
    display: flex;
    font-size: 12px;

    .left {
      width: 69%;
      // height: 600px;
      .table-con {
        height: 500px;
      }
    }
    .right {
      margin-left: 1%;
      width: 30%;

      .list-con {
        height: 500px;
      }
    }
  }

  .auto-create-package-con {
    // height: 600px;
    width: 100%;
    li {
      width: 100%;
      border: 1px solid #e5e6eb;
      padding: 5px 0;
      .top {
        width: 100%;
        display: flex;
        justify-content: space-between;
        padding: 0 10px;
      }

      .line {
        width: 100%;
        margin: 10px 0;
        border-top: 1px solid #e5e6eb;
      }

      .bottom {
        padding: 0 10px;
        margin: 10px;
      }
    }
  }
</style>
